package net.khoroshev.wschat.web;

import java.security.Principal;
import java.util.Collection;
import java.util.Date;

import net.khoroshev.wschat.model.ChatHistoryEntry;
import net.khoroshev.wschat.service.ChatService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ChatController {

    @Autowired
    ChatService chatService;
    
    private static final Log logger = LogFactory.getLog(ChatController.class);
    @MessageMapping("/chat")
    public void message(Principal principal, String text) {
        logger.debug("Message from user " + principal.getName() + ": " + text);
        chatService.onMessage(new ChatHistoryEntry(principal.getName(), new Date(), text));
    }

    @MessageExceptionHandler
    @SendToUser("/queue/errors")
    public String handleException(Throwable exception) {
        return exception.getMessage();
    }

    @RequestMapping(value="/chatHistory")
    public @ResponseBody Collection<ChatHistoryEntry>
        getHistory(@RequestParam(defaultValue="100") int qty) {
        Collection<ChatHistoryEntry> result = null;
        if (qty > 0) {
            result = chatService.getLastMessages(qty);
        }
        return result;
    }

}
